package com.abhinav.designPatterns.proxy;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

public class ProxyExample {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Animal realSubject = new Lion();
		Animal proxy = (Animal) Proxy.newProxyInstance(
				realSubject.getClass().getClassLoader(), 
				realSubject.getClass().getInterfaces(), 
				new AnimalInvocationHandler(realSubject));
		
		proxy.getSound();
	}
}

interface Animal {
	public void getSound();
}

class Lion implements Animal {
	public void getSound() {
		System.out.println("Roar");
	}
}

class AnimalInvocationHandler implements InvocationHandler {
	private Object realSubject = null;

	public AnimalInvocationHandler(Object realSubject) {
		this.realSubject = realSubject;
	}

	@Override
	public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
		Object result = null;
		try {
			result = method.invoke(realSubject, args);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
		return result;
	}
}